package com.btpj.jwt.filter;

import com.btpj.jwt.entity.RespBean;
import com.btpj.jwt.entity.User;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.*;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.FilterChain;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.Date;

/**
 * jwt登录过滤器
 *
 * @author BTPJ  2020/8/18
 */
public class JwtLoginFilter extends AbstractAuthenticationProcessingFilter {

    public JwtLoginFilter(String defaultFilterProcessesUrl, AuthenticationManager authenticationManager) {
        // 需要拦截的登录Url
        super(new AntPathRequestMatcher(defaultFilterProcessesUrl));
        setAuthenticationManager(authenticationManager);
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws AuthenticationException, IOException {
        User user = new ObjectMapper().readValue(httpServletRequest.getInputStream(), User.class);
        return getAuthenticationManager().authenticate(new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword()));
    }

    @Override
    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException {
        // 登录成功回调
        Collection<? extends GrantedAuthority> authorities = authResult.getAuthorities(); //获取登录用户的角色
        StringBuffer sb = new StringBuffer();
        authorities.forEach(it -> sb.append(it.getAuthority()).append(","));
        String jwt = Jwts.builder()
                .claim("authorities", sb) // 配置用户角色
                .setSubject(authResult.getName())
                // Token过期时间 20天
                .setExpiration(new Date(System.currentTimeMillis() + 20 * 24 * 60 * 60 * 1000))
                .signWith(SignatureAlgorithm.HS512, "BTPJ")
                .compact();
        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();
        User user = (User) authResult.getPrincipal();
        user.setToken(jwt);
        out.write(new ObjectMapper().writeValueAsString(RespBean.success(user, "登录成功")));
        out.flush();
        out.close();
    }

    @Override
    protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException {
        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();
        RespBean respBean = RespBean.error(e.getMessage());
        if (e instanceof LockedException) {
            respBean.setMsg("账户被锁定，请联系管理员!");
        } else if (e instanceof AccountExpiredException) {
            respBean.setMsg("账户过期，请联系管理员!");
        } else if (e instanceof DisabledException) {
            respBean.setMsg("账户被禁用，请联系管理员!");
        } else if (e instanceof BadCredentialsException) {
            respBean.setMsg("用户名或者密码输入错误，请重新输入!");
        }
        out.write(new ObjectMapper().writeValueAsString(respBean));
        out.flush();
        out.close();
    }
}
